<?php
if(!defined('IN_THANKPHP_SYSTEM')) exit('Access Denied!');

class mysql extends model {
	const TYPE_UPDATE = 'update';
	const TYPE_INSERT = 'insert';
	
	public function connect($config) {
		extract($config);
		$link = @mysql_connect($HOST, $USER, $PASSWORD);
		if (!$link) {
			$this->error("Could not connect:$USER@$HOST");
		}
		$status =  @mysql_select_db($NAME, $link);
		if (!$status) {
			$this->error("Could not select db: $NAME");
		}
		return $this->link = $link;
	}

	public function query($sql){
		$this->handle = @mysql_query($sql);
		if(!$this->handle){
			$this->error('Query error:'.$sql);
		}
		return $this->handle;
	}
	
	public function update($table, $array, $key = 'id'){
		list($q,$condition) = $this->parse($array, self::TYPE_UPDATE, $key);
		$sql = "UPDATE {$table} SET {$q} WHERE {$condition}";
		return $this->query($sql);
	}
	
	public function insert($table, $array){
		$q = $this->parse($array, self::TYPE_INSERT); 
		$sql = "INSERT INTO {$table}{$q}";
		return $this->query($sql);
	}
	
	public function insertId(){
		$this->insert_id = @mysql_insert_id($this->link);
		return $this->insert_id;
	}
	
	public function delete($table, $condition){
		$sql = "DELETE FROM {$table} WHERE {$condition}";
		return $this->query($sql);
	}
	
	public function getOne(){
		$this->result = @mysql_fetch_array($this->handle, MYSQL_ASSOC);
		return $this->result;
	}
	
	public function fetchArray(){
		$r = $data = array();
		while($r = @mysql_fetch_array($this->handle, MYSQL_ASSOC)){
			$data[] = $r;
		}
		return $data;
	}
	
	public function error($error){
		$this->error_msg = $error;
		if($this->getDebug()){
			print $this->error_msg;
			exit;
		}
		return $this->error_msg;
	}
	
	public function parse($array, $type, $key = 'id'){
		$str = '';
		switch($type){
			case self::TYPE_UPDATE:	{
				//v1=1,v2=2 WHERE id = 1;
				$str = $q =array();
				foreach($array AS $k=>$v){
					if($k != $key){
						$q[] = "{$k}  = '{$v}'";
					}
				}
				$q_s = join(',', $q);
				$str[] = $q_s;
				$str[] = "{$key} = '{$array[$key]}'";
				break;
			}
			case self::TYPE_INSERT:	{
				//(v1,v2) VALUES('1', '2')
				$q1=$q2=array();
				foreach($array AS $k=>$v){
					$q1[] = "`{$k}`";
					$q2[] = "'{$v}'";
				}
				$q1_s = join(',', $q1);
				$q2_s = join(',', $q2);
				$str = "({$q1_s}) VALUES({$q2_s})";
				break;
			}
			default:{
				$this->error('Could not parse this type:');
				break;
			}
		}
		return $str;
	}
}
